package com.myself.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author W.S.
 * @version v4.0.0
 * @description nio 客户端
 * @date Created in 2018/9/5 17:15
 */
public class NioClient {
    private Selector selector;

    //缓存区大小容量
    private final static int BUF_SIZE = 1024;

    public void test1() throws IOException{
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        selector = Selector.open();
        socketChannel.register(selector, SelectionKey.OP_CONNECT);
        socketChannel.connect(new InetSocketAddress(8686));

    }

    public void listen() throws IOException{
        while(true){
            SocketChannel client = null;
            selector.select();
            Set<SelectionKey> sets = selector.selectedKeys();
            Iterator<SelectionKey> iterator = sets.iterator();
            while(iterator.hasNext()){
                SelectionKey key = iterator.next();
                iterator.remove();
                if(key.isConnectable()){
                    System.out.println("客户端监听到连接事件");
                    client = (SocketChannel) key.channel();
                    if(client.isConnectionPending()){
                        client.finishConnect();
                        ByteBuffer send = ByteBuffer.allocate(BUF_SIZE);
                        send.put("我是客户端发送给服务端的消息".getBytes());
                        send.flip();
                        client.write(send);
                        //client.register(selector,SelectionKey.OP_READ);
                    }
                }else if(key.isReadable()){
                    System.out.println("客户端监听到读事件");
                    client = (SocketChannel) key.channel();
                    ByteBuffer receive = ByteBuffer.allocate(BUF_SIZE);
                    receive.clear();
                    int length = client.read(receive);
                    if(length > 0){
                        System.out.println("客户端接收到："+new String(receive.array(),0,length));
                    }
                }
            }
            sets.clear();
        }
    }

    public static void main(String[] args) {
        NioClient client = new NioClient();
        try {
            client.test1();
            client.listen();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
